import React, { useEffect, useState } from 'react';
import { Card, Form, Input, Button, Table, Tag, Select, Space, message } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { getConnectorList, ConnectorInfo, ConnectorListParams } from '../../../services/connector';
import './styles.css';

const { Option } = Select;

const ConnectorList: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<ConnectorInfo[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 获取连接器列表数据
  const fetchConnectorList = async (params: ConnectorListParams = {}) => {
    try {
      setLoading(true);
      const { current = 1, size = 10, ...restParams } = params;
      const response = await getConnectorList({
        current,
        size,
        ...restParams,
      });
      setData(response.records);
      setPagination({
        current: response.current,
        pageSize: response.size,
        total: response.total,
      });
    } catch (error) {
      message.error('获取连接器列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 首次加载
  useEffect(() => {
    fetchConnectorList();
  }, []);

  const columns = [
    {
      title: '基础支撑平台',
      dataIndex: 'platform',
      key: 'platform',
      width: 150,
      render: () => '上海（SH）',

    },
    {
      title: '连接器名称',
      dataIndex: 'connectorName',
      key: 'connectorName',
      width: 200,
    },
    {
      title: '连接器类型',
      dataIndex: 'connectorType',
      key: 'connectorType',
      width: 120,
      render: (type: string) => {
        const typeMap: Record<string, string> = {
          STANDARD: '标准版',
          PROFESSIONAL: '专业版',
          ENTERPRISE: '企业版',
        };
        return typeMap[type] || type;
      }
    },
    {
      title: '连接器状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status: string) => {
        const statusMap = {
          ACTIVE: { text: '已激活', color: 'success' },
          INACTIVE: { text: '未激活', color: 'default' },
          SUSPENDED: { text: '已暂停', color: 'warning' },
        };
        const { text, color } = statusMap[status as keyof typeof statusMap] || { text: status, color: 'default' };
        return <Tag color={color}>{text}</Tag>;
      }
    },
    {
      title: '服务提供方',
      dataIndex: 'provider',
      key: 'provider',
      width: 200,
    },
    {
      title: '最后访问时间',
      dataIndex: 'lastAccessTime',
      key: 'lastAccessTime',
      width: 180,
    },
    {
      title: 'AccessKey',
      dataIndex: 'accessKey',
      key: 'accessKey',
      width: 200,
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
    }
  ];

  // 处理搜索
  const handleSearch = async (values: any) => {
    try {
      await fetchConnectorList({
        ...values,
        current: 1,
        size: pagination.pageSize,
      });
    } catch (error) {
      console.error('搜索失败:', error);
    }
  };

  // 处理重置
  const handleReset = () => {
    form.resetFields();
    fetchConnectorList({
      current: 1,
      size: pagination.pageSize,
    });
  };

  // 处理表格变化
  const handleTableChange = (pagination: any, filters: any, sorter: any) => {
    fetchConnectorList({
      current: pagination.current,
      size: pagination.pageSize,
      ...form.getFieldsValue(),
      ...filters,
    });
  };

  return (
    <div>
      <Card bordered={false}>
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 24 }}
        >
          <Form.Item name="connectorName" label="连接器名称">
            <Input placeholder="请输入连接器名称" allowClear />
          </Form.Item>
          <Form.Item name="connectorType" label="连接器类型">
            <Select placeholder="请选择连接器类型" allowClear style={{ width: 200 }}>
              <Option value="STANDARD">标准版</Option>
              <Option value="PROFESSIONAL">专业版</Option>
              <Option value="ENTERPRISE">企业版</Option>
            </Select>
          </Form.Item>
          <Form.Item name="status" label="连接器状态">
            <Select placeholder="请选择连接器状态" allowClear style={{ width: 200 }}>
              <Option value="ACTIVE">已激活</Option>
              <Option value="INACTIVE">未激活</Option>
              <Option value="SUSPENDED">已暂停</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>

        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`
          }}
          onChange={handleTableChange}
        />
      </Card>
    </div>
  );
};

export default ConnectorList; 